package ide.ccf.ccproject.wizards.pages;

import ide.ccf.ccproject.ProjectPlugin;
import ide.ccf.ccproject.common.Utils;
import ide.ccf.ccproject.preferences.CCFPreferencePage;
import ide.ccf.ccproject.preferences.PreferenceConstants;
import ide.ccf.ccproject.translate.Message;

import java.io.File;
import java.io.IOException;

import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Path;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.preference.PreferenceDialog;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.MouseListener;
import org.eclipse.swt.events.MouseTrackListener;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.dialogs.PreferencesUtil;

/**
 * Qt项目导入向导页面
 *
 */
public class ImportQtWizardPage extends WizardPage implements SelectionListener, ModifyListener 
{
	private Table list;
	private Text profilelocation;
	private IPath pathToProFile = null;
	public Combo c_sdk;
	public Combo c_runtime;
	
	/**
	 * 构造器
	 * @param pageName
	 */
	public ImportQtWizardPage(String pageName) 
	{
		super(pageName);
		setTitle(pageName);
		setDescription(Message.ImportQtWizardPage_0);
		setPageComplete(false);
	}
	
   private Listener nameModifyListener = new Listener() {
        public void handleEvent(Event e) {
        	if(c_sdk.getText().isEmpty() || c_runtime.getText().isEmpty())
        		setPageComplete(false);
        	else
        		setPageComplete(true);
        }
    };
	    

	/**
	 * 向导页面创建控制
	 */
	public void createControl(Composite parent) 
	{
		Composite workArea = new Composite(parent, SWT.NONE);
		setControl(workArea);

		GridLayout layout = new GridLayout();
		layout.numColumns = 3;
		layout.verticalSpacing = 10;
		
		workArea.setLayout(layout);
		workArea.setLayoutData(new GridData(GridData.FILL_BOTH | GridData.GRAB_HORIZONTAL | GridData.GRAB_VERTICAL));
		
		Label label = new Label(workArea, SWT.NONE);
		label.setText(Message.ImportQtWizardPage_1);
		
		profilelocation = new Text(workArea, SWT.BORDER);
		profilelocation.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
		profilelocation.addModifyListener(this);
		
		Button browse = new Button(workArea, SWT.NONE);
		browse.setText(Message.UiFileWizardPage_11);
		browse.addSelectionListener(this);
		
		list = new Table(workArea, SWT.CHECK | SWT.BORDER);
		list.addSelectionListener(this);
		GridData data = new GridData(GridData.FILL_BOTH);
		data.horizontalSpan = 3;
		list.setLayoutData(data);
		
		final Group g = new Group(workArea,SWT.NONE);
		g.setText(Message.CCProjectWizardOnePage_0);
		GridData gd1 = new GridData(GridData.FILL_BOTH);
		gd1.horizontalSpan = 3;
		gd1.heightHint = 70;
		g.setLayoutData(gd1);
		GridLayout layout2 = new GridLayout(2,false);
		layout2.verticalSpacing = 10;
		g.setLayout(layout2);
		{
			Label l_1 = new Label(g, SWT.NONE);
			l_1.setText(Message.CCProjectWizardOnePage_1);
			l_1.setFont(g.getFont());
			l_1.setLayoutData(new GridData(GridData.BEGINNING));
			c_sdk = new Combo(g, SWT.DROP_DOWN | SWT.READ_ONLY);
			c_sdk.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
			c_sdk.setFont(workArea.getFont());
			c_sdk.addListener(SWT.Modify, nameModifyListener);
			Label l_2 = new Label(g, SWT.NONE);
			l_2.setText(Message.CCProjectWizardOnePage_2);
			l_2.setFont(g.getFont());
			l_2.setLayoutData(new GridData(GridData.BEGINNING));
			c_runtime = new Combo(g, SWT.DROP_DOWN | SWT.READ_ONLY);
			c_runtime.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
			c_runtime.setFont(g.getFont());
			c_runtime.addListener(SWT.Modify, nameModifyListener);
			
			String[] strRuntimeVersions = getCCFRuntimeVersions();
			String[] strSdkVersions = getCCFSdkVersions();
			if(strRuntimeVersions != null)
			{
				c_runtime.setItems(strRuntimeVersions);
				for(int i = 0; i < strRuntimeVersions.length; i++)
					c_runtime.setData(strRuntimeVersions[i]);
			}
			if(strSdkVersions != null)
			{
				c_sdk.setItems(strSdkVersions);
				for(int j = 0; j < strSdkVersions.length; j++)
					c_sdk.setData(strSdkVersions[j]);
			}
			c_sdk.setText(CCFPreferencePage.getCCFSdkVersion() == null ? "" : CCFPreferencePage.getCCFSdkVersion());
			c_runtime.setText(CCFPreferencePage.getCCFRuntimeVersion() == null ? "" : CCFPreferencePage.getCCFRuntimeVersion());
			
			Label l_occupy = new Label(g, SWT.RIGHT);
			l_occupy.setText("");
			
			final Label l_3 = new Label(g, SWT.RIGHT| SWT.HORIZONTAL );
			l_3.setText(Message.CCProjectWizardOnePage_3);
			l_3.setLayoutData(new GridData(GridData.FILL_BOTH));
			l_3.setFont(g.getFont());
			Color color = new Color(null, 238, 99, 99);
			l_3.setForeground(color);
			l_3.addMouseTrackListener(new MouseTrackListener(){
				public void mouseEnter(MouseEvent e) {
					Color color = new Color(null, 139, 58, 58);
					//l_3.setForeground(Display.getCurrent().getSystemColor(SWT.COLOR_BLUE));
					l_3.setForeground(color);
					l_3.setCursor(Display.getCurrent().getSystemCursor(SWT.CURSOR_HAND));
				}
				public void mouseExit(MouseEvent arg0) {
					Color color = new Color(null, 238, 99, 99);
					l_3.setForeground(color);
				}
				public void mouseHover(MouseEvent e) {	
				}
			});
			l_3.addMouseListener(new MouseListener()
			{
				public void mouseDoubleClick(MouseEvent e) {
				}
				public void mouseDown(MouseEvent e) {
					PreferenceDialog dialog = PreferencesUtil.createPreferenceDialogOn(getShell(), "ide.ccf.ccproject.preferences.CCFPreferencePage", null, null);
					int type = dialog.open();
					if(type == dialog.OK)
					{
						c_sdk.setText(CCFPreferencePage.getCCFSdkVersion() == null ? "" : CCFPreferencePage.getCCFSdkVersion());
						c_runtime.setText(CCFPreferencePage.getCCFRuntimeVersion() == null ? "" : CCFPreferencePage.getCCFRuntimeVersion());
						//strRuntime = c_runtime.getText().trim();
						//strSdk = c_sdk.getText().trim();
					}
					else if(type == dialog.CANCEL)
					{
						
					}
				}
				public void mouseUp(MouseEvent e) {
				}
			});
		}
	}

	/**
	 * 从用户设置路径提取pro文件名称
	 * @return
	 */
	public String getProjectName() 
	{
		return Utils.getFileName(pathToProFile, true);
	}

	/**
	 * 提取pro文件所在路径
	 * @return
	 */
	public IPath getProFileLocation() 
	{
		return Utils.removeFileName(pathToProFile);
	}

	/**
	 * 默认选择
	 */
	public void widgetDefaultSelected(SelectionEvent e) 
	{
		
	}

	/**
	 * pro文件选择
	 */
	public void widgetSelected(SelectionEvent e) 
	{
		if (e.widget == list) 
		{
			updatePage();			
		} 
		else 
		{
			FileDialog filedlg = new FileDialog(getShell());
			
			String[] filterext = {Message.ImportQtWizardPage_2}; 
			String[] filtername = {Message.ImportQtWizardPage_3};
			
			filedlg.setFilterExtensions(filterext);
			filedlg.setFilterNames(filtername);
			filedlg.setText(Message.ImportQtWizardPage_4);
			
			String filename = filedlg.open();
			
			if (filename != null)
				profilelocation.setText(filename);
		}
	}
	
	/**
	 * 更新向导页面
	 */
	private void updatePage() 
	{
		setErrorMessage(null);
		boolean enabled = false;
		
		for (int i = 0; i < list.getItemCount(); ++i) 
		{
			if (list.getItem(i).getChecked()) 
			{
				enabled = true;
				break;
			}
		}
		
		if (!checkProFileLocation())
			enabled = false;
		
		setPageComplete(enabled);
	}

	/**
	 * 检查pro文件路径
	 * @return
	 */
	private boolean checkProFileLocation() 
	{
		try 
		{
			String rootPath = ResourcesPlugin.getWorkspace().getRoot().getLocation().toFile().getCanonicalPath();
			String proPath = getProFilePath().toFile().getCanonicalPath();
			//System.out.println("rootPath:"+rootPath);
			//System.out.println("proPath:"+proPath);
			
			if (proPath.startsWith(rootPath)) 
			{
				setErrorMessage(Message.ImportQtWizardPage_5);
				return false;
			}
		} 
		catch (IOException e) 
		{
			setErrorMessage(Message.ImportQtWizardPage_6);
			return false;
		}
		return true;
	}
	
	/**
	 * 文本改变时发送事件
	 */
	public void modifyText(ModifyEvent e) 
	{
		list.removeAll();
		
		if (isValidProFile()) 
		{
			TableItem item = new TableItem(list, SWT.NONE);
			item.setText(getProjectName());
			item.setChecked(true);
		}
		updatePage();		
	}
	
	/**
	 * 获取pro项目文件路径
	 * @return
	 */
	private IPath getProFilePath() 
	{
		return new Path(profilelocation.getText().trim());
	}
	
	/**
	 * 遍历文件夹下所有文件
	 * @param filePath
	 */
	static boolean getFiles(String filePath){
		  File root = new File(filePath);
		    File[] files = root.listFiles();
		    for(File file:files){    
		     if(file.isDirectory()){//如果path表示的是一个目录则返回true
		      /*
		       * 递归调用
		       */
		      getFiles(file.getAbsolutePath());
		      System.out.println("显示"+filePath+"下所有子目录及其文件"+file.getAbsolutePath());
		     }else{
		      System.out.println("显示"+filePath+"下所有子目录"+file.getAbsolutePath());
		     }    
		     if(file.getAbsolutePath().endsWith(".pro"))
		    	 return true;
		     else
		    	 return false;
		    }
			return false;
		 }
	
	/**
	 * 是否合法的pro文件
	 * @return
	 */
	private boolean isValidProFile() 
	{
		pathToProFile = getProFilePath();
		//System.out.println("\\\\\\\\\\\\\\\\"+pathToProFile);
		//System.out.println("/////////////////////"+ pathToProFile.getFileExtension());
		if(pathToProFile.isEmpty() || (null == pathToProFile.getFileExtension() ))
			return false;
		
		if (!pathToProFile.getFileExtension().equals("pro"))
		return false;
		
		File file = pathToProFile.toFile();
		if (!file.exists())
			return false;
		
		return true;
	}
	
	public static String[] getCCFSdkVersions() {
		if(ProjectPlugin.getDefault() != null)
		{
			IPreferenceStore store = ProjectPlugin.getDefault().getPreferenceStore();
			
			if (!store.contains(PreferenceConstants.CCFSDK_VERSIONS))
				return null;
			
			String defaultVersions = store.getString(PreferenceConstants.CCFSDK_VERSIONS);
			defaultVersions = defaultVersions.substring(1, defaultVersions.length()-1);
			//System.out.println("defaultVersions:"+defaultVersions);
			//cut string
			String[] b = defaultVersions.split(",");
			if(b.length > 0)
				return b;	
		}
		return null;
	}

	public static String[] getCCFRuntimeVersions() {
		if(ProjectPlugin.getDefault() != null)
		{
			IPreferenceStore store = ProjectPlugin.getDefault().getPreferenceStore();
			
			if (!store.contains(PreferenceConstants.CCFRUNTIME_VERSIONS))
				return null;
			
			String defaultVersions = store.getString(PreferenceConstants.CCFRUNTIME_VERSIONS);
			defaultVersions = defaultVersions.substring(1, defaultVersions.length()-1);
			//System.out.println("defaultVersions:"+defaultVersions);
			//cut string
			String[] b = defaultVersions.split(",");
			if(b.length > 0)
				return b;	
		}
		return null;
	}
}
